<template>
  <div class="bg">
    <div class="signIN" v-show="show">
      <div>
        <el-form ref="formsignIN" :model="signIn" :rules="signINrules" label-width="80px">
          <el-form-item label="欢迎登录"></el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input placeholder="请输入邮箱" v-model="signIn.email"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
              <el-input placeholder="请输入密码" type="password" v-model="signIn.password"></el-input>
            </el-form-item>
        </el-form>
      </div>
      <div class="signINbutton">
         <el-button style="width:185px;" :disabled="disabled" size="medium"  @click="clicksignIn" type="primary">登录</el-button>
         <el-button style="width:185px;" :disabled="disabled" type="success" @click="goregister">注册</el-button>
      </div>
      <div class="retrievePassword">
        <span @click="dialogPass = true" style="cursor: pointer;">找回密码&nbsp;</span>
        <span @click="$router.push('/client/clientHome')" style="cursor: pointer;">/ 回到主页</span>
      </div>
    </div>
    <div class="register" v-show="!show">
      <div>
        <el-form ref="formregister" :rules="registerrules" :model="register" label-width="80px">
          <el-form-item label="欢迎注册"></el-form-item>
          <el-form-item label="头像" class="imgform" prop="user_pic">
            <div v-if="register.user_pic != ''">
               <el-image
                  @click="$refs.imgfile.click()"
                  style="width:60px;height:60px;cursor: pointer;"
                  :src="register.user_pic"
                  :fit="'fit'">
                </el-image>
            </div>
            <div v-else @click="$refs.imgfile.click()" class="addimg">
              +
            </div>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input placeholder="请输入邮箱" v-model="register.email"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input placeholder="请输入昵称" v-model="register.nickname"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
              <el-input placeholder="请输入密码" type="password" v-model="register.password"></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="username">
              <el-input placeholder="请输入姓名" type="text" v-model="register.username"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="signINbutton">
         <el-button style="width:185px;" :disabled="disabled" size="medium"  @click="clickregister" type="primary">注册</el-button>
         <el-button style="width:185px;" :disabled="disabled" type="success" @click="revert">返回</el-button>
      </div>
    </div>
    <input type="file" ref="imgfile" v-show="false"  @change="addimg()"/>
    <edit-pass @closedialogPassword="closedialogPassword" :dialogPass="dialogPass"></edit-pass>
  </div>
</template>

<script>
import editPass from '../../components/editPassword.vue'
import * as imageConversion from 'image-conversion'
export default {
  components: {
		'edit-pass':editPass
  },
  data(){
    var validateemail = (rule,value, callback) => {
      let re = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
        if (value === '') {
          callback(new Error('请输入邮箱'));
        } else if(re.test(value)){
          callback();
        } else {
          callback(new Error('请输入正确的邮箱'));
        }
      };
    var validatepassword = (rule,value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else if(value.length >= 6 && value.length <= 18){
          callback();
        } else {
          callback(new Error('请输入6-18位的密码'));
        }
      };
    return{
      signIn:{
        email:'',
        password:''
      },
      dialogPass:false,
      disabled:false,
      register:{
        nickname:'',
        username:'',
        password:'',
        email:'',
        user_pic:''
      },
      show:true,
      signINrules:{
        password: [
            { validator: validatepassword, trigger: 'blur' }
          ],
        email: [
            { validator: validateemail, trigger: 'blur' },
          ],
      },
      registerrules:{
          password: [
              {required: true,validator: validatepassword, trigger: 'blur' }
          ],
          email: [
              {required: true,validator: validateemail, trigger: 'blur' },
          ],
          nickname: [
            { required: true, message: '请输入昵称', trigger: 'blur' },
            { min: 1, max: 12, message: '昵称最长位12个字符', trigger: 'blur' }
          ],
          username: [
            { required: true, message: '请输入姓名', trigger: 'blur' }
          ],
          user_pic: [
            {required: true, message: '请添加头像', trigger: 'change' }
          ],
      },
    }
  },
  methods:{
    closedialogPassword(){
			this.dialogPass = false
		},
    clicksignIn(){
      this.$refs['formsignIN'].validate((valid) => {
          if (valid) {
            this.disabled = true
            let denglu = {
              email:this.signIn.email,
              password:this.$md5(this.signIn.password)
            }
            this.$http.post('/api/login',denglu).then(res => {
              if(res.status == 0){
                this.$message({
                  message: '恭喜您登录成功！',
                  type: 'success'
                });
                this.$user_pic = res.message.user_pic
                this.$userInfo.username = res.message.username
                this.$userInfo.nickname = res.message.nickname
                this.$userInfo.email = res.message.email
                this.$userInfo.power = res.message.power
                this.$userInfo.pagePower = res.message.pagePower
                this.$userInfo._id = res.message._id
                this.$userInfo.token = res.token
                localStorage.setItem("user_pic",this.$user_pic)
                localStorage.setItem("token",res.token)
                localStorage.setItem("userInfo",escape(JSON.stringify(this.$userInfo)))
                setTimeout(() => {
                  if(this.$router.history._startLocation == "/record"){
                  this.$router.push("/client/clientHome");
                  return
                }
                if(this.$userInfo.power != 1){
                  this.$router.push("/client/clientHome");
                  return
                }
                this.$router.push(this.$router.history._startLocation);
                },1000)
              }else{
                this.$message({
                  message: res.message,
                  type: 'error'
                });
              }
              this.disabled = false
            }).catch(err => {
              this.disabled = false
              this.$message({
                  message: err,
                  type: 'error'
                });
            })
          }
        });
    },
    //参加注册
    goregister(){
      this.$refs['formsignIN'].resetFields()
      this.show = false
    },
    //返回登录
    revert(){
      this.$refs['formregister'].resetFields()
      this.show = true
      this.register = {
        nickname:'',
        username:'',
        password:'',
        email:'',
        user_pic:''
      }
    },
    //注册
    clickregister(){
      this.$refs['formregister'].validate((valid) => {
          if (valid) {
            this.disabled = true
            let list = this.register
            list.password = this.$md5(this.register.password)
            this.$http.post('/api/reguser',this.register).then(res => {
              if(res.status == 0){
                this.$message({
                  message: '恭喜您注册成功，欢迎您登录！',
                  type: 'success'
                });
                this.revert()
              }else{
                this.$message({
                  message: res.message,
                  type: 'error'
                });
              }
              this.disabled = false
            }).catch(err => {
              this.disabled = false
              this.$message({
                  message: err,
                  type: 'error'
                });
            })
          }
      })
    },
    //添加图片
    async addimg(){
      if(this.$refs.imgfile.files.length == 0) return
      let name = ['jpg','png','jpge']
      let na = this.$refs.imgfile.files[0].name.split('.')
      let i = name.findIndex(item => item.toLocaleUpperCase() == na[1].toLocaleUpperCase())
      if(i == -1){
        this.$message.warning('仅支持png、jpg、jpge格式图片')
        return
      }
      if(this.$refs.imgfile.files[0].size/1024/1024 > 3){
        this.$message.warning('头像最大支持3MB')
        return
      }
      let files = this.$refs.imgfile.files[0];
      let file = await this.compressImg(files)
      var reader = new FileReader();
      reader.readAsDataURL(file); //调用自带方法进行转换
      reader.onload = (e) => {
        this.register.user_pic = e.target.result
        this.$refs.formregister.validateField('user_pic')
      }
    },
    compressImg(file){
      return new Promise((resolve, reject) => {
          imageConversion.compressAccurately(file, 30).then(res => {
            res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
            resolve(res)
          })
      })
    },
  }
}
</script>


<style scoped>
.bg{
  background-color: #FA8BFF;
  background-image: linear-gradient(45deg, #FA8BFF 0%, #2BD2FF 52%, #2BFF88 90%);
  position:fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
}
.signIN{
  width: 420px;
  height: 250px;
  background-color: white;
  border-radius: 20px;
  box-shadow: 1px 1px 1px 1px #c5c1c1;
  padding: 40px;
}
.signINbutton{
  display: flex;
  justify-content: flex-end;
}
.register{
  width: 420px;
  height: 430px;
  background-color: white;
  border-radius: 20px;
  box-shadow: 1px 1px 1px 1px #c5c1c1;
  padding: 40px;
}
.retrievePassword{
  display: flex;
  justify-content: center;
  color: #2BD2FF;
  font-size: 8px;
  padding-top: 20px;
}
.addimg{
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #aca8a8;
  color: #aca8a8;
  cursor: pointer;
}
div /deep/.imgform .el-form-item__content {
    position: relative;
    font-size: 14px;
    line-height: 0;
}

</style>